package chef.myapplication.controller;

import chef.myapplication.Main;
import chef.myapplication.model.*;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.NodeOrientation;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.input.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Screen;
import javafx.stage.Stage;


import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;

public class FunctionUIController implements Initializable {


    @FXML
    private StackPane stackPane;//容器
    private final ImageView iv =new ImageView();//图片
    private final BorderPane borderPane = new BorderPane();//功能页
    private  final Stage stage= ImageBoxes.getFunctionUIStage();//舞台

    private final Label count =new Label();

    /*
    下方工具栏   可通过getItem()add(); 添加button
     */
    private final ToolBar toolBar= new ToolBar();//基本工具栏

    private final ToolBar displayBar =new ToolBar();//ppt模式工具栏

    private int currentIndex=0;//图片的Index
    private double winWidth;//窗口大小
    private double winHeight;
    private double sysRation;//窗口比例
    private final HBox beautyBox = new HBox();//美化工具栏
    private Image image = new Image(String.valueOf(ImageBoxes.getCurrentImageFile().toURI()));//图片
    private  WritableImage wImage;
    private final HBox toolBox = new HBox();//下方工具盒的容器

    private Timer timer;

    private long delay = 3000;//Timer 延迟时间
    private long period = 3000;//Timer 间隔时间

    private boolean flag = false;
    private MyButton btnAct=null;//暂停播放



    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        init();
    }
    /*
    底层为图片层
    顶层为操作层
     */
    public void init(){
        stage.centerOnScreen();
        File currentFile = ImageBoxes.getCurrentImageFile();
        iniStackPane();
        iv.setPreserveRatio(true);
        getScreenSize();
        Image image=new Image(currentFile.toURI().toString());
        currentIndex= FileTree.getImageFiles().indexOf(currentFile);
        initView(image);
        initActionPane();
        initDisplayBar();
    }
    /*
    初始化stackPane
     */
    private void iniStackPane() {
        stackPane.getChildren().add(iv);
        stackPane.setPrefSize(winWidth, winHeight);
        stackPane.setStyle("-fx-background-color:\t#FFFFFF");

        stackPane.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            if (!event.getButton().equals(MouseButton.PRIMARY)){
                return;
            }
            if(event.getX()<winWidth/2){
                showPre();
            }
            else {
                showNext();
            }
        });
        stackPane.addEventHandler(KeyEvent.ANY, event -> {
            System.out.println(event);
            if (event.getCode().equals(KeyCode.LEFT))
                showPre();
            if (event.getCode().equals(KeyCode.RIGHT)) {
                showNext();
            }
        });
        stackPane.addEventHandler(ScrollEvent.SCROLL,event -> {
            if(event.getDeltaY()>0){
                zoomIn();
            }else {
                zoomOut();
            }
        });

    }

    /*
    得到窗口尺寸
     */
    private void getScreenSize() {
        Rectangle2D rectangle2D = Screen.getScreens().get(0).getBounds();
        winHeight = rectangle2D.getHeight() / 1.45;
        winWidth = rectangle2D.getWidth() / 1.45;
        sysRation= winWidth / winHeight;
    }

    /*
    初始化操作页
     */
    private void initActionPane(){
        /*
        布局设置
         */
        borderPane.setLeft(count);
        setCount();
        stackPane.getChildren().add(borderPane);
        initToolBar();
        initBeauty();
    }
    private void setCount(){
        count.setText(String.format("%d/%d",currentIndex+1,ImageBoxes.getImageBoxes().size()));
    }
    /*
    初始化美化工具栏
     */
    private void initBeauty() {
        Button bright = new Button("明亮");
        Button darker = new Button("深暗");
        Button gray = new Button("灰度处理");
        Button invert = new Button("颜色反转");
        Button saturate  = new Button("增加饱和度");
        Button desaturate = new Button("减少饱和度");
        Button recover = new Button("还原图片");
        Button hide = new Button("隐藏");
        bright.setOnAction(event -> pixWithImage(0));

        darker.setOnAction(event -> pixWithImage(1));

        gray.setOnAction(event -> pixWithImage(2));

        invert.setOnAction(event -> pixWithImage(3));

        saturate.setOnAction(event -> pixWithImage(4));

        desaturate.setOnAction(event -> pixWithImage(5));

        hide.setOnAction(event -> beautyBox.setVisible(false));

        recover.setOnAction(event -> iv.setImage(image));
        ToolBar toolBeauty  = new ToolBar(bright,darker,gray,invert,saturate,desaturate,recover,hide);
        beautyBox.setAlignment(Pos.CENTER);
        beautyBox.setVisible(false);
        toolBeauty.setStyle("-fx-background-color: transparent");
        beautyBox.getChildren().add(toolBeauty);
        borderPane.setTop(beautyBox);
    }
    /*
    图片美化处理
     */
    private void pixWithImage(int type){
        PixelReader pixelReader = iv.getImage().getPixelReader();
        // Create WritableImage
        wImage = new WritableImage(
                (int)image.getWidth(),
                (int)image.getHeight());
        PixelWriter pixelWriter = wImage.getPixelWriter();
        for(int y = 0; y < wImage.getHeight(); y++){
            for(int x = 0; x < wImage.getWidth(); x++){
                Color color = pixelReader.getColor(x, y);
                switch (type) {
                    case 0 -> color = color.brighter();
                    case 1 -> color = color.darker();
                    case 2 -> color = color.grayscale();
                    case 3 -> color = color.invert();
                    case 4 -> color = color.saturate();
                    case 5 -> color = color.desaturate();
                    default -> {
                    }
                }
                pixelWriter.setColor(x, y, color);
            }
        }
        iv.setImage(wImage);
    }

    /*
    下一张
     */
    private void showNext() {
        //System.out.println("showNext"+currentIndex);
        currentIndex++;
        setCount();
        if (currentIndex==ImageBoxes.getImageBoxes().size()){
            if (timer!=null){
            timer.cancel();
            }
            currentIndex--;
            setCount();
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.titleProperty().set("提示");
            alert.headerTextProperty().set("这是最后1张图片");
            alert.showAndWait();
            return;
        }
        image = new Image(FileTree.getImageFiles().get(currentIndex).toURI().toString());
        initView(image);
        if (timer==null){
        setCount();
        }
    }
    /*
    上一张
     */
    private void showPre() {

        if (currentIndex==0){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.titleProperty().set("提示");
            alert.headerTextProperty().set("这是第1张图片");
            alert.showAndWait();
            return;
        }
        currentIndex--;
        setCount();
        image=new Image(FileTree.getImageFiles().get(currentIndex).toURI().toString());
        initView(image);
    }

    /*
    设置初始工具栏
    工具栏的重复代码太多，得重写
     */
    private void initToolBar() {
        int iconWidth =30;
        /*/
        前一张
         */
        ImageView left = new ImageView(new Image(Objects.requireNonNull(Main.class.getResource("icon/箭头-左.png")).toString()));
        MyButton btnLeft = new MyButton(left,iconWidth);
        Tooltip tooltipLeft = new Tooltip("上一张");
        btnLeft.setTooltip(tooltipLeft);
        btnLeft.setOnAction(event -> {
            showPre();
            event.consume();
        });
        /*
        后一张
        */
        ImageView right = new ImageView(new Image(Objects.requireNonNull(Main.class.getResource("icon/箭头-右.png")).toString()));
        MyButton btnRight = new MyButton(right,iconWidth);
        Tooltip tooltipRight = new Tooltip("下一张");
        btnRight.setTooltip(tooltipRight);
        btnRight.setOnAction(event -> {
            showNext();
            event.consume();
        });
        /*
        旋转
         */
        ImageView leftRotate = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/左旋转.png")).toString());
        MyButton btnLeftRotate =new MyButton(leftRotate,iconWidth);
        Tooltip tooltipLeftRotate = new Tooltip("向左旋转90度");
        btnLeftRotate.setTooltip(tooltipLeftRotate);
        btnLeftRotate.setOnAction(event -> leftRotate());

        ImageView rightRotate = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/右旋转.png")).toString());
        MyButton btnRightRotate =new MyButton(rightRotate,iconWidth);
        Tooltip tooltipRightRotate = new Tooltip("向右旋转90度");
        btnRightRotate.setTooltip(tooltipRightRotate);
        btnRightRotate.setGraphic(rightRotate);
        btnRightRotate.setStyle("-fx-background-color: transparent");
        btnRightRotate.setOnAction(event -> rightRotate());
        /*
        左右互换
         */
        ImageView DaoZhi = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/左右互换.png")).toString());
        MyButton btnDaoZhi =new MyButton(DaoZhi,iconWidth);
        Tooltip tooltipDaoZhi = new Tooltip("左右互换");
        btnDaoZhi.setTooltip(tooltipDaoZhi);
        btnDaoZhi.setOnAction(event -> DaoZhi());
        /*
        鼠标靠近显示
        退出隐藏
         */
        toolBox.setOnMouseEntered(event -> toolBox.getChildren().get(0).setVisible(true));
        toolBox.setOnMouseExited(event -> toolBox.getChildren().get(0).setVisible(false));
        toolBox.setAlignment(Pos.BOTTOM_CENTER);
        ImageView display = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/播放.png")).toString());
        MyButton btnDisplay =new MyButton(display,iconWidth);
        Tooltip tooltipDisplay = new Tooltip("PPT");
        btnDisplay.setTooltip(tooltipDisplay);
        btnDisplay.setOnAction(event -> display());
        /*
        放大缩小
         */
        ImageView zoomIn = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/放大.png")).toString());
        MyButton btnZoomIn =new MyButton(zoomIn,iconWidth);
        Tooltip tooltipZoomIn = new Tooltip("放大");
        btnZoomIn.setTooltip(tooltipZoomIn);
        btnZoomIn.setOnAction(event -> zoomIn());

        ImageView zoomOut = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/缩小.png")).toString());
        MyButton btnZoomOut = new MyButton(zoomOut,iconWidth);
        Tooltip tooltipZoomOut = new Tooltip("缩小");
        btnZoomOut.setTooltip(tooltipZoomOut);
        btnZoomOut.setOnAction(event -> zoomOut());
        /*
        图片美化
         */
        ImageView beauty = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/美化图片.png")).toString());
        MyButton btnBeauty = new MyButton(beauty,iconWidth);
        Tooltip tooltipBeauty = new Tooltip("美化");
        btnBeauty.setTooltip(tooltipBeauty);
        btnBeauty.setOnAction(event -> beauty());
        /*
        图片另存为
         */
        ImageView export = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/另存为.png")).toString());
        MyButton btnExport = new MyButton(export,iconWidth);
        Tooltip tooltipExport = new Tooltip("另存为");
        btnExport.setTooltip(tooltipExport);
        btnExport.setGraphic(export);
        btnExport.setOnAction(event ->export());
        /*
        全屏
         */
        ImageView fullScreen = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/全屏.png")).toString());
        MyButton btnFullScreen = new MyButton(fullScreen,iconWidth);
        Tooltip tooltipFullScreen = new Tooltip("全屏");
        btnFullScreen.setTooltip(tooltipFullScreen);
        btnFullScreen.setOnAction(event -> stage.setFullScreen(!stage.isFullScreen()));
        /*
        删除
         */
        ImageView delete = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/删除.png")).toString());
        MyButton btnDelete = new MyButton(delete,iconWidth);
        Tooltip tooltipDelete = new Tooltip("删除");
        btnDelete.setTooltip(tooltipDelete);
        btnDelete.setOnAction(event -> {
            if(MyAlert.showAlert1("是否删除选中的图片？", "", stage.getOwner()))
            {
                System.out.println("delete");
                ImageBoxes.getImageBoxes().get(currentIndex).delete();
                MainController.getMainController().Refresh();
                System.out.println(ImageBoxes.getImageBoxes());
                if (ImageBoxes.getImageBoxes().size()==0){
                    System.out.println("舞台关闭");
                    stage.close();
                    Main.getMainStage().show();
                    return;
                }
                if (currentIndex==0){
                    showNext();
                    currentIndex=0;
                }
                else {
                    showPre();
                }
            }
            else {
                System.out.println("取消删除");
            }
            setCount();
        });
        /*
        toolbar的导入
         */
        toolBar.getItems().addAll(btnLeft,btnRight,btnZoomIn,btnZoomOut,btnLeftRotate,btnRightRotate,btnDaoZhi,btnDisplay,btnBeauty,btnExport,btnFullScreen,btnDelete);
        toolBox.setStyle("");
        toolBox.getChildren().add(toolBar);
        borderPane.setBottom(toolBox);
    }
    private void export() {
        wImage = iv.snapshot(new SnapshotParameters(),null);
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("图片文件", "*.png","*.jpg", "*.bmp", "*.gif"));
        File file = fileChooser.showSaveDialog(stage.getOwner());
        if (file != null) {
            try {
                ImageIO.write(SwingFXUtils.fromFXImage(wImage, null), "png", file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    美化按钮的执行函数
     */
    private void beauty() {
        beautyBox.setVisible(true);
    }
    /*
    放大的执行函数
     */
    private void zoomIn() {
        iv.setScaleX(iv.getScaleX() * 1.25);
        iv.setScaleY(iv.getScaleY() * 1.25);
    }
    /*
      缩小的执行函数
     */
    private void zoomOut() {
        iv.setScaleX(iv.getScaleX() * 0.75);
        iv.setScaleY(iv.getScaleY() * 0.75);
    }
    /*
    左右倒置
     */
    private void DaoZhi() {
        if (iv.getNodeOrientation().name().equals("RIGHT_TO_LEFT")) {
            iv.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT);
        } else {
            iv.setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT);
        }
    }
    /*
    界面初始化
     */
    private void initView(Image image){
        iv.getTransforms().clear();
        iv.setScaleX(1);
        iv.setScaleY(1);
        iv.setImage(image);
        iv.fitWidthProperty().unbind();
        iv.fitHeightProperty().unbind();
        iv.fitWidthProperty().set(0);
        iv.fitHeightProperty().set(0);
        double imageRation = image.getWidth()/ image.getHeight();
        if(image.getWidth()> winWidth ||image.getHeight()> winHeight){//图片大于窗口
            if(sysRation<imageRation){
                iv.fitWidthProperty().bind(stackPane.widthProperty());
                System.out.println(iv.fitHeightProperty());
                System.out.println("width bind");
            }
            else{
                iv.fitHeightProperty().bind(stackPane.heightProperty());
                System.out.println("height bind");
            }
        }
        else{
            System.out.println("图片小于窗口");
            iv.fitWidthProperty().setValue(image.getWidth());
        }
    }


    private void initDisplayBar(){
        int iconWidth = 15;
        ImageView stop = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/暂停.png")).toString());
        ImageView act =new ImageView("file:src/main/resources/icon/播放.png");
        Label  labelDelay = new Label("间隔3秒");
        stop.setFitWidth(iconWidth);
        stop.setPreserveRatio(true);
        act.setPreserveRatio(true);
        act.setFitWidth(iconWidth);
        btnAct= new MyButton("暂停",stop,iconWidth);
        btnAct.setOnAction(event -> act(stop, act));
        ImageView add = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/加.png")).toString());
        MyButton btnAdd = new MyButton(add,iconWidth);
        btnAdd.setOnAction(event -> {
            if (delay==10000)
                return;
            delay = delay+1000;
            period = period+1000;
            if (timer!=null){
            timer.cancel();}
            setTimer();
            String string = String.format("间隔%d秒",delay/1000);
            labelDelay.setText(string);
        });
        ImageView sub = new ImageView(Objects.requireNonNull(Main.class.getResource("icon/减.png")).toString());
        MyButton btnSub = new MyButton(sub,iconWidth);
        btnSub.setOnAction(event -> {
            if (delay==1000)
                return;
            delay = delay-1000;
            period = period-1000;
            if(timer!=null){
            timer.cancel();}
            setTimer();
            String string = String.format("间隔%d秒",delay/1000);
            labelDelay.setText(string);
        });
        Button btnExit = new Button("退出");
        ImageView reSet =  new ImageView(Objects.requireNonNull(Main.class.getResource("icon/重来.png")).toString());
        MyButton btnReSet = new MyButton(reSet,iconWidth);
        btnReSet.setOnAction(event -> reSet(stop));
        displayBar.getItems().addAll(btnReSet,btnAct,btnAdd,labelDelay,btnSub,btnExit);
        btnExit.setOnAction(event -> exit());
    }
    /*
    播放暂停
     */
    private void act(ImageView stop, ImageView act) {
        if(currentIndex==ImageBoxes.getImageBoxes().size()-1){
            return;
        }
        if(!flag){
            btnAct.setText("继续播放");
            btnAct.setGraphic(act);
            if (timer!=null) {
                timer.cancel();
            }
        }
        else {
           setTimer();
           btnAct.setGraphic(stop);
           btnAct.setText("暂停");
        }
        flag = !flag;
    }

    /*
    退出ppt
     */
    private void exit() {
        stage.setFullScreen(false);
        toolBox.getChildren().clear();
        toolBox.getChildren().add(toolBar);
        if(timer!=null) {
            timer.cancel();
        }
    }

    private void reSet(ImageView stop) {
        btnAct.setGraphic(stop);
        btnAct.setText("暂停");
        if (timer!=null){
            timer.cancel();
        }
        currentIndex=0;
        setCount();
        iv.setImage(new Image(ImageBoxes.getImageBoxes().get(currentIndex).getFile().toURI().toString()));
        setTimer();
    }

    /*
     * 左旋转90
     */
    public void leftRotate()
    {
        iv.setRotate((iv.getRotate() - 90) % 360);
    }
    /*
     * 右旋转90
     */
    public void rightRotate()
    {
        iv.setRotate((iv.getRotate() + 90) % 360);
    }
    private void setTimer() {
        if(currentIndex==ImageBoxes.getImageBoxes().size()-1){
            btnAct.setText("播放完毕");
            ImageView imageView =new ImageView(Objects.requireNonNull(Main.class.getResource("icon/播放.png")).toString());
            imageView.setPreserveRatio(true);
            imageView.setFitWidth(15);
            btnAct.setGraphic(imageView);
            return;
        }
        timer = new Timer(true);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    if (currentIndex==ImageBoxes.getImageBoxes().size()-2) {
                        btnAct.setText("播放完毕");
                        ImageView imageView =new ImageView(Objects.requireNonNull(Main.class.getResource("icon/播放.png")).toString());
                        imageView.setPreserveRatio(true);
                        imageView.setFitWidth(15);
                        btnAct.setGraphic(imageView);
                        timer.cancel();
                        showNext();
                        setCount();
                        Alert alert = new Alert(Alert.AlertType.INFORMATION,"幻灯片播放完毕！");
                        alert.showAndWait();
                        return;
                    }
                    showNext();
                    setCount();
                });
            }
        };
        timer.schedule(timerTask,delay,period);
    }
    /*/
    幻灯片
     */
    private void display(){
        stage.setFullScreen(true);
        toolBox.getChildren().clear();
        toolBox.getChildren().add(displayBar);
        setTimer();
    }
}
